package filter;

import user.Fruit;
import util.DBUtilDao;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class FruitFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        DBUtilDao dbutilDao = new DBUtilDao();

        List<Fruit> fruit = null; //获取水果信息
        try {
            fruit = dbutilDao.getFruit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        for (Fruit fruit1 : fruit) {
            if (fruit1.getName().equals("apple")) {
                session.setAttribute("apple", fruit1.getPrice());//苹果价格
            }
            if (fruit1.getName().equals("orange")) {
                session.setAttribute("orange", fruit1.getPrice());//橘子价格
            }
        }
        try {
            dbutilDao.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
